/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package g4h.android.monterhunt;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

import g4h.android.monterhunt.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
 
/**
 * This class provides a basic demonstration of how to write an Android
 * activity. Inside of its window, it places a single view: an EditText that
 * displays and edits some internal text.
 */
public class MonsterHunt extends MapActivity {
    
    static final private int BACK_ID = Menu.FIRST;
    static final private int CLEAR_ID = Menu.FIRST + 1;

    private ImageView pic;
    private TextView txt;
    
    private MapView map;
    private MapController controller;

    private GameState state;
    
    public MonsterHunt() {
    }
    /** Find and initialize the map view. */
    private void initMapView() {
       map = (MapView) findViewById(R.id.map);
       controller = map.getController();
       map.setSatellite(true);
       map.setBuiltInZoomControls(true);
       
       //slap some monsters on the screen
       Drawable monMark = getResources().getDrawable(R.drawable.violet);
       monMark.setBounds(0,0,monMark.getIntrinsicWidth(),monMark.getIntrinsicHeight());
       map.getOverlays().add(new Monsters(monMark));
       
    }
    

    
    /** Start tracking the position on the map. */
    private void initMyLocation() {
       final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
       overlay.enableMyLocation(); 
       //overlay.enableCompass(); // does not work in emulator
       overlay.runOnFirstFix(new Runnable() {
          public void run() {
             // Zoom in to current location
             controller.setZoom(16);
             controller.animateTo(overlay.getMyLocation());
          }
       });
       map.getOverlays().add(overlay);
    }
    
    
    public void updateGUI(){
    	LinearLayout mapLayout = (LinearLayout)findViewById(R.id.maplayout);
    	LinearLayout regLayout = (LinearLayout)findViewById(R.id.regularlayout);
    	
    	Button backBttn = (Button)findViewById(R.id.back);
    	Button nextBttn = (Button)findViewById(R.id.next);


    	if(state.getLevel().equals(GameState.State.map)){
    		//setContentView(R.layout.map);
    		mapLayout.setVisibility(View.VISIBLE);
    		regLayout.setVisibility(View.INVISIBLE);
    		
    	}else if(state.getLevel().equals(GameState.State.monster_disappear)){
    //		setContentView(R.layout.hunt_layout);
            pic = (ImageView) findViewById(R.id.storypic);
            txt = (TextView) findViewById(R.id.storytext);
            
    		pic.setImageResource(state.getLevel().getPicResource());
    		txt.setText(state.getLevel().getStringResource());
    		
    		mapLayout.setVisibility(View.INVISIBLE);
    		regLayout.setVisibility(View.VISIBLE);
    		
    		nextBttn.setVisibility(View.VISIBLE);
    		backBttn.setVisibility(View.VISIBLE);
    		

    	}else if(state.getLevel().equals(GameState.State.congrats)){//last
    		pic.setImageResource(state.getLevel().getPicResource());
    		txt.setText(state.getLevel().getStringResource());
    		
    		mapLayout.setVisibility(View.INVISIBLE);
    		regLayout.setVisibility(View.VISIBLE);
    		
    		nextBttn.setVisibility(View.INVISIBLE);
    		backBttn.setVisibility(View.VISIBLE);
    		
    	}else if(state.getLevel().equals(GameState.State.intro)){//first
    		pic.setImageResource(state.getLevel().getPicResource());
    		txt.setText(state.getLevel().getStringResource());
    		
    		mapLayout.setVisibility(View.INVISIBLE);
    		regLayout.setVisibility(View.VISIBLE);
    		
    		nextBttn.setVisibility(View.VISIBLE);
    		backBttn.setVisibility(View.INVISIBLE);
    		
    	}else if(state.getLevel().equals(GameState.State.try_catch)){//try and catch
    		pic.setImageResource(state.getLevel().getPicResource());
    		txt.setText(state.getLevel().getStringResource());
    		
    		mapLayout.setVisibility(View.INVISIBLE);
    		regLayout.setVisibility(View.VISIBLE);
    		
    		nextBttn.setVisibility(View.INVISIBLE);
    		backBttn.setVisibility(View.INVISIBLE);
    	}else{
    		pic.setImageResource(state.getLevel().getPicResource());
    		txt.setText(state.getLevel().getStringResource());
    		
    		mapLayout.setVisibility(View.INVISIBLE);
    		regLayout.setVisibility(View.VISIBLE);
    		
    		nextBttn.setVisibility(View.VISIBLE);
    		backBttn.setVisibility(View.VISIBLE);

    	}
    	
    }
    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        state = new GameState();
        
        // Inflate our UI from its XML layout description.
        setContentView(R.layout.hunt_layout);

        // Find the text editor view inside the layout, because we
        // want to do various programmatic things with it.
        pic = (ImageView) findViewById(R.id.storypic);
        txt = (TextView) findViewById(R.id.storytext);

        // Hook up button presses to the appropriate event handler.
        ((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
        ((Button) findViewById(R.id.next)).setOnClickListener(mNextListener);
        this.initMapView();
        this.initMyLocation();
        
        LocationManager locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        
        
        //HUZZA! Inline class interentance! Take that clean coding style!
        LocationListener locListener = new LocationListener()
        {
        	public void onLocationChanged(Location location){
        		if(location != null){
        			Location monLoc = new Location(location);
        			monLoc.setLatitude(40.00728442499995);
        			monLoc.setLongitude(-105.26178);
        			Log.v("GPS", "location changed "+ location.getLatitude() +","+location.getLongitude());
        			
        			float dist = location.distanceTo(monLoc);
        			Log.v("GPS", "dist to eye = "+ dist +"Metres");

        			if(state.getLevel().equals(GameState.State.map) && dist < 75){
        				Log.v("GPS", "close enough to eye: "+ dist);
        				state.nextLevel();
        				updateGUI();
        			}
        			//else if (state.getLevel().equals(GameState.State.show_monster) && dist < 250){
        				//state.previousLevel();
        			//}
        			
        		}
        	}

			@Override
			public void onProviderDisabled(String arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderEnabled(String arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
				// TODO Auto-generated method stub
				
			}
        };
        //FIXME This is the correct way to do things
        //locMgr.addProximityAlert(latitude, longitude, radius, expiration, intent);
        
        locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
        updateGUI();
       // pic.setImageResource(state.getLevel().getPicResource());
    }

    /**
     * Called when the activity is about to start interacting with the user.
     */
    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * Called when your activity's options menu needs to be created.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // We are going to create two menus. Note that we assign them
        // unique integer IDs, labels from our string resources, and
        // given them shortcuts.
        menu.add(0, BACK_ID, 0, R.string.back).setShortcut('0', 'b');
        menu.add(0, CLEAR_ID, 0, R.string.next).setShortcut('1', 'n');

        return true;
    }

    /**
     * Called right before your activity's option menu is displayed.
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        // Before showing the menu, we need to decide whether the clear
        // item is enabled depending on whether there is text to clear.

        return true;
    }

    /**
     * Called when a menu item is selected.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case BACK_ID:
        	state.previousLevel();
        	updateGUI();
            return true;
        case CLEAR_ID:
        	state.nextLevel();
        	updateGUI();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A call-back for when the user presses the back button.
     */
    OnClickListener mBackListener = new OnClickListener() {
        public void onClick(View v) {
        	state.previousLevel();
        	updateGUI();
           // pic.setImageResource(state.getLevel().getPicResource());

        }
    };

    /**
     * A call-back for when the user presses the clear button.
     */
    OnClickListener mNextListener = new OnClickListener() {
        public void onClick(View v) {
        	state.nextLevel();
        	updateGUI();
           // pic.setImageResource(state.getLevel().getPicResource());

        }
    };

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}
